﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AgencyEntityLib.BaseEntity;
using System.Web.UI.WebControls;
using Ecopsy.DataTier;

using FormControllers;
using System.Text;

namespace AgencyEntityLib.BaseEntity
{
    

    /// <summary>
    /// Визуальное предтавление в гриднике
    /// </summary>
    public class grdTask
    {
        protected   BaseTask _Task = null;
        public grdTask(BaseTask t) { _Task = t; }

        public virtual BaseTask Task { get { return _Task; } }
        public virtual string s_TaskContent { get { return _Task.TaskContent; } }
        public virtual string s_Type { get { return _Task.GetTxtTaskType(); } }

        public virtual string s_dtFinish { get { return (_Task.dtFinish.Year == GlobalConstants.MinDate.Year ? string.Empty : _Task.dtFinish.ToShortDateString()); } }
        public virtual DateTime dtFinish { get { return _Task.dtFinish; } }
        public virtual int FinishTime { get { return (dtFinish.Hour == 0 ? 8 : dtFinish.Hour); } }        
        public virtual string s_Employeer
        {
            get
            {
                if (string.Empty == _Task.EmplID) return string.Empty;
                //wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
                Employeer r = GetEmpl();
                if (null == r) return string.Empty;
                return r.ShortName;

            }
        }
        public virtual string s_EmployeerWithPosition
        {
            get
            {
                if (string.Empty == _Task.EmplID) return string.Empty;
                wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
                Employeer r = GetEmpl();
                if (null == r) return string.Empty;
                return r.GetFullNameWithDepartmentPosition ();

            }
        }
        public virtual string RowCss
        {
            get
            {
                if (s_Closed == "Просроченна") return "OverTimeTask";
                else
                    return "grd_tr_item";

            }
             
        }
        public string HistoryofMessage 
        {
            get 
            {
                StringBuilder res = new StringBuilder();
                foreach (grdTaskHistoryitem item in _Task.GetHistroyItems())
                {
                    if (res.ToString().Trim().IndexOf(item._Task.TaskContent.Trim()) > -1)
                        continue;
                      
                    res.Append(item.Date.ToShortDateString()+":" + item._Task.TaskContent+"\n");
 
                }
                return res.ToString ();
            }
        }


        /// <summary>
        /// Часы в представлении времени
        /// </summary>
        public ListItem[] Hours 
        {
            get 
            {
                ListItem[] res = new ListItem[12];
                bool isSel = false;
                bool isSelChanged = false;
                for (int i = 8; i < 20; i++)
                {
                    res[i-8] = new ListItem();
                    res[i - 8].Value = i.ToString();
                    isSel=(i.ToString() == dtFinish.Hour.ToString());
                    if (isSel) isSelChanged = true;
                    res[i - 8].Selected = isSel;

                }
                if (!isSelChanged) res[0].Selected = true;
                return res;
            }
        }
        public virtual string s_Closed
        {
            get
            {
                return (_Task.GetTaskStatusName());
            }
        }
        public virtual string s_Client
        {
            get
            {
                if (string.Empty == _Task.ClientID) return string.Empty;
                wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
                Client r = ws.GetClient(_Task.ClientID);
                return r.Name;
            }
        }        
        public virtual string s_EmployeerShort
        {
            get
            {
                if (string.Empty == _Task.EmplID) return string.Empty;
                wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
                Employeer r = GetEmpl();
                if (null == r) return string.Empty;
                return r.FirstName;
            }
        }     
        private Employeer GetEmpl()
        {
            if (string.Empty == _Task.EmplID) return null;
            wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
            return ws.GetEmpl(_Task.EmplID);
        }

    }

    public class grdTaskHistoryitem:grdTask 
    {
        public grdTaskHistoryitem(BaseTask  t):base (t)
        {

        }
        public Employeer Creator {get; set;}
        public DateTime Date {get; set;}

    }
        
    public static class TaskExt
    {       
        public static List<grdTaskHistoryitem> GetHistroyItems(this BaseTask _Task)
        {
            List<grdTaskHistoryitem> res = new List<grdTaskHistoryitem>();

            var sortedНistory =
            from d in _Task.History.ToArray < TaskHistoryItem>()
            orderby d.Date descending
            select d;

            foreach (TaskHistoryItem item in sortedНistory.ToArray<TaskHistoryItem>())
            {
                res.Add(new grdTaskHistoryitem(item.Task)  { Creator = item.Creator, Date = item.Date });
            }
            return res;
        }
        
        /// <summary>
        /// Достает из списка задач задачи - удовлетворяющие функции  Fetch_Where
        /// сейчас - используется календарем д отбора задач за период
        /// </summary>
        /// <param name="_TaskList"></param>
        /// <param name="Fetch_Where"></param>
        /// <returns></returns>
        public static List<Task> Fetch(this TaskList _TaskList, Func<Task, bool> Fetch_Where)
        {

            List<Task> res = new List<Task>();
            _TaskList.Reset();
            foreach (Task item in _TaskList)
            {
                if (Fetch_Where(item)) res.Add(item);

            }
            return res;

        }
                
        /// <summary>
       /// конвертировать список задач в список представляемый в гриднике 
       /// </summary>
       /// <param name="List"></param>
       /// <returns></returns>
        public static grdTask[] ToGrdTask(ICollection<Task> List)
        {
            List<grdTask> res = new List<grdTask>();
            foreach (Task item in List)
            {
                res.Add(new grdTask(item));
            }
            return res.ToArray<grdTask>();
        }

        public static string GetTxtTaskType(this BaseTask _Task)
        {
            return TreeDictionaryContext.GetPropertyVal(_Task.TypeValue);
        }

        

        
        
    }
}